package com.imooc.distributedemo.resume.leetcode;

/**
 * 数组拼接最大的数值字符串
 */
public class SolutionMaxStrFromArray {
    public static void main(String[] args) {
//        int[] array = {10,8,5,24,4,51};
        int[] array = {10,1};
        String str = maxStr(array);
        System.out.println(str);
    }

    private static String maxStr(int[] array) {
        if(null==array||array.length==0){
            return "";
        }

        int sum=0;
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        if(sum==0){
            return "0";
        }

        String result = "";
        int size = array.length;
        for (int i = 0; i < size-1; i++) {
            for (int j = 0; j < (size-1-i); j++) {
                boolean b = compare(array[j],array[j+1]);
                if(b){
                    // swap(array[j],array[j+1]);
                    int temp = array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                }
            }
        }
        for (int i = 0; i < size; i++) {
            result = result+String.valueOf(array[i]);
        }
        return result;
    }

    private static void swap(int num1, int num2) {
        int tmp = num1;
        num1=num2;
        num2=tmp;
    }

    private static boolean compare(int num1, int num2) {

        // 判断两个数值高位有重叠的部分
        String s1 = String.valueOf(num1);
        String s2 = String.valueOf(num2);
        // num1=54 num2=542  那么返回true。  num1在前面，不需要交换
        if(s2.startsWith(s1)){
            return false;
        }else{
            int hightLoc1 = getHighLoc(num1);
            int hightLoc2 = getHighLoc(num2);
            if(hightLoc1<hightLoc2){
                return true;
            }else{
                return false;
            }
        }
    }

    private static int getHighLoc(int num) {
        int hightLoc;
        if(num<10){
            hightLoc = num;
        }else{
            int tmp = num;
            while (tmp>=10){
                tmp /= 10;
            }
            hightLoc = tmp;
        }
        return hightLoc;
    }
    private void m1(){
        System.out.println("m1;");
    }

    private void m2(){
        System.out.println("m2;");
        this.m1();
    }
}
